package qingke.hibernate.dao;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.query.Query;

import qingke.hibernate.bean.Student;
import qingke.hibernate.bean.StudentLogin;
import qingke.hibernate.bean.StudentStatus;

public class StudentDao {
	private Session session;

	public StudentDao(Session session) {
		this.session = session;
	}

	public List<Student> list() {
		Query<Student> query = session.createQuery("from Student", Student.class);

		return query.getResultList();
	}

	public Student getById(int id) {

		return session.get(Student.class, id);
	}
	
	public StudentStatus getStatusById(int id) {

		return session.get(StudentStatus.class, id);
	}
	
	public StudentLogin getBuID(int id ){
		return session.get(StudentLogin.class, id);
	}

	public List<Student> ListByName(String name) {
		Query<Student> query = session.createQuery("from Student where firstname like :name or lastname like:name",
				Student.class);

		query.setParameter("name", "%" + name + "%");
		return query.getResultList();
	}
	public Student load(int id){
		return session.load(Student.class, id);
	}


	public void insert(Student student) {
		Transaction tx = session.beginTransaction();
		try {
			session.save(student);
			tx.commit();
		} catch (HibernateException e) {
			e.printStackTrace();
			tx.rollback();
		}
	}

	public void update(Student student) {
		Transaction tx = session.beginTransaction();
		try {
			session.update(student);
			tx.commit();
		} catch (HibernateException e) {
			e.printStackTrace();
			tx.rollback();
		}
	}

	public void delete(Student student) {
		Transaction tx = session.beginTransaction();
		try {
			session.delete(student);
			tx.commit();
		} catch (HibernateException e) {
			e.printStackTrace();
			tx.rollback();
		}
	}

}
